package br.com.cicero.tarefas.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.cicero.tarefas.dao.TarefaDAO;
import br.com.cicero.tarefas.model.Tarefa;

@Controller
public class TarefasController {
	
	private final TarefaDAO tarefaDao;
	
	@Autowired
	public TarefasController(TarefaDAO tarefaDao) {
		this.tarefaDao = tarefaDao;
	}
		
	@RequestMapping("novaTarefa")
	public String form() {
		return "tarefa/formulario";
	}
	
	@RequestMapping("adicionaTarefa")
	public String adiciona(@Valid Tarefa tarefa, BindingResult result) {
		if (result.hasFieldErrors("descricao")) {
			return "tarefa/formulario";
		} 
		tarefaDao.adiciona(tarefa);
		return "tarefa/adicionada";
	}
	
	@RequestMapping("listaTarefas")
	public String lista(Model model) {
		model.addAttribute("tarefas", tarefaDao.getLista());
		return "tarefa/lista";
	}
	
	@RequestMapping("removeTarefa")
	public void remove(Tarefa tarefa, HttpServletResponse response) {
		tarefaDao.remove(tarefa.getId());
		response.setStatus(200);
	}
	
	@RequestMapping("mostraTarefa")
	public String mostra(Long id, Model model) {
		model.addAttribute("tarefa", tarefaDao.buscaPorId(id));
		return "tarefa/mostra";
	}
	
	@RequestMapping("alteraTarefa")
	public String altera(Tarefa tarefa) {
		tarefaDao.altera(tarefa);
		return "redirect:listaTarefas";
	}
	
	@RequestMapping("finalizaTarefa")
	public String finaliza(Long id, Model model) throws IOException {
		tarefaDao.finaliza(id);
		model.addAttribute("tarefa", tarefaDao.buscaPorId(id));
		return "tarefa/finalizada";
	}
	
}
